<template>
  <RadModal
    :visible="visible"
    :loading="loading"
    :isUpdate="isUpdate"
    title="作业信息"
    @visibleChange="updateVisible"
    is-fullscreen
    @ok="save"
  >
    <a-tabs>
      <a-tab-pane key="0" tab="作业信息" :active="true" :force-render="true">
        <a-form :model="form" ref="formRef" label-width="130px">
          <a-row :gutter="35">
            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <a-form-item
                label="作业编号"
                name="jobId"
                :rules="[
                  {
                    required: true,
                    message: '作业编号不能为空',
                    trigger: 'blur'
                  }
                ]"
              >
                <a-input
                  v-model:value="form.jobId"
                  placeholder="作业编号"
                  :disabled="isEdit"
                  clearable
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <a-form-item
                label="组名称"
                name="groupName"
                :rules="[
                  { required: true, message: '组名称不能为空', trigger: 'blur' }
                ]"
              >
                <a-input
                  v-model:value="form.groupName"
                  placeholder="组名称"
                  clearable
                />
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <a-form-item label="创建类型" name="createType">
                <a-radio-group
                  v-model:value="form.createType"
                  :disabled="isEdit"
                >
                  <a-radio :value="JobCreateTypeEnum.NUMBER_0" v-show="isEdit"
                    >内置</a-radio
                  >
                  <a-radio :value="JobCreateTypeEnum.NUMBER_1">脚本</a-radio>
                  <a-radio :value="JobCreateTypeEnum.NUMBER_2"
                    >Http请求</a-radio
                  >
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
              <a-form-item label="执行方式" name="concurrent">
                <a-radio-group v-model:value="form.concurrent">
                  <a-radio :value="true">并行</a-radio>
                  <a-radio :value="false">串行</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col
              :xs="24"
              :sm="12"
              :md="12"
              :lg="12"
              :xl="12"
              class="mb20"
              v-show="!isEdit && !isHttpCreateType"
            >
              <a-form-item name="includeAnnotations">
                <template #label>
                  <div>
                    扫描特性触发器
                    <a-tooltip
                      raw-content
                      title="此参数只在新增作业时生效<br/>扫描定义在作业上的触发器"
                      placement="top"
                    >
                      <QuestionCircleFilled />
                    </a-tooltip>
                  </div>
                </template>
                <a-radio-group v-model:value="form.includeAnnotations">
                  <a-radio :value="true">是</a-radio>
                  <a-radio :value="false">否</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
              <a-form-item label="描述信息" name="description">
                <a-textarea
                  :rows="4"
                  placeholder="描述信息"
                  v-model:value="form.description"
                />
              </a-form-item>
            </a-col>
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              class="mb20"
              v-if="!isHttpCreateType"
            >
              <a-form-item label="额外数据" name="properties">
                <a-textarea
                  :rows="6"
                  placeholder="额外数据"
                  v-model:value="form.properties"
                />
              </a-form-item>
            </a-col>
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              class="mb20"
              v-if="isHttpCreateType"
            >
              <a-form-item label="请求地址" name="requestUri">
                <a-input
                  v-model:value="state.httpJobMessage.requestUri"
                  placeholder="请求地址"
                  clearable
                />
              </a-form-item>
            </a-col>
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              class="mb20"
              v-if="isHttpCreateType"
            >
              <a-form-item label="请求方法" name="httpMethod">
                <a-radio-group v-model:value="state.httpJobMessage.httpMethod">
                  <a-radio :value="httpMethodDef.get">Get</a-radio>
                  <a-radio :value="httpMethodDef.post">Post</a-radio>
                  <a-radio :value="httpMethodDef.put">Put</a-radio>
                  <a-radio :value="httpMethodDef.delete">Delete</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
            <a-col
              :xs="24"
              :sm="24"
              :md="24"
              :lg="24"
              :xl="24"
              class="mb20"
              v-if="isHttpCreateType"
            >
              <a-form-item label="请求报文体" name="body">
                <a-textarea
                  :rows="6"
                  placeholder="请求报文体"
                  v-model:value="state.httpJobMessage.body"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-tab-pane>
      <a-tab-pane
        key="1"
        tab="脚本代码"
        :force-render="true"
        :disabled="!isScriptCreateType"
      >
        <div ref="monacoEditorRef" style="width: 100%; height: 500px"></div>
      </a-tab-pane>
    </a-tabs>
  </RadModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { message } from 'ant-design-vue/es';
  import { QuestionCircleFilled } from '@ant-design/icons-vue';
  import * as monaco from 'monaco-editor';
  import type { FormInstance } from 'ant-design-vue/es/form';
  import RadModal from '@/components/RadModal/index.vue';
  import useFormData from '@/utils/use-form-data';
  import { add, update } from '@/api/system/job';
  import {
    UpdateJobDetailInput,
    JobCreateTypeEnum
  } from '@/api/system/job/model';
  import { JobScriptCode } from './JobScriptCode';

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const monacoEditorRef = ref();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: UpdateJobDetailInput | null;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<UpdateJobDetailInput>(
    {
      id: 0,
      groupName: '',
      jobType: '',
      assemblyName: '',
      description: '',
      concurrent: true,
      includeAnnotations: false,
      properties: '',
      createType: 2,
      scriptCode: '',
      jobId: ''
    }
  );

  const httpMethodDef = {
    get: '{"Method":"GET"}',
    post: '{"Method":"POST"}',
    put: '{"Method":"PUT"}',
    delete: '{"Method":"DELETE"}'
  };
  const state = reactive({
    isShowDialog: false,
    selectedTabName: '0', // 选中的 tab 页
    httpJobMessage: {
      requestUri: '',
      httpMethod: httpMethodDef.get,
      body: ''
    } as HttpJobMessage
  });

  // 是否编辑状态
  const isEdit = computed(() => {
    return form.id != undefined && form.id > 0;
  });

  // 是否脚本创建类型
  const isScriptCreateType = computed(() => {
    return form.createType === JobCreateTypeEnum.NUMBER_1;
  });

  // 是否Http请求创建类型
  const isHttpCreateType = computed(() => {
    return form.createType === JobCreateTypeEnum.NUMBER_2;
  });
  // // 表单验证规则
  // const rules = reactive<Record<string, Rule[]>>({
  //   name: [
  //     {
  //       required: true,
  //       message: '请输入名称',
  //       type: 'string',
  //       trigger: 'blur'
  //     }
  //   ],
  //   code: [
  //     {
  //       required: true,
  //       message: '请输入编码',
  //       type: 'string',
  //       trigger: 'blur'
  //     }
  //   ],
  //   order: [
  //     {
  //       required: true,
  //       message: '请输入排序',
  //       type: 'number',
  //       trigger: 'blur'
  //     }
  //   ],
  //   value: [
  //     {
  //       required: true,
  //       message: '请输入值',
  //       type: 'string',
  //       trigger: 'blur'
  //     }
  //   ]
  // });

  /* 保存编辑 */
  const save = () => {
    debugger;
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        // 脚本创建类型
        if (form.createType === JobCreateTypeEnum.NUMBER_1) {
          form.scriptCode = monacoEditor.getValue();
        } else {
          form.scriptCode = '';
        }

        // Http请求创建类型
        if (form.createType === JobCreateTypeEnum.NUMBER_2) {
          // 将 httpJobMessage 重新封装，按后端 HttpJob 序列化要求，字段要大写开头
          // HttpJob 约定读取属性为“HttpJob”的值
          const httpJobPropValue = JSON.stringify({
            RequestUri: state.httpJobMessage.requestUri,
            HttpMethod: JSON.parse(state.httpJobMessage.httpMethod + ''),
            Body: state.httpJobMessage.body,
            ClientName: 'HttpJob',
            EnsureSuccessStatusCode: true
          });
          const prop = { HttpJob: httpJobPropValue };
          form.properties = JSON.stringify(prop);
        }
        const saveOrUpdate = isUpdate.value ? update : add;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };
  // 初始化monacoEditor对象
  var monacoEditor: any = null;
  const initMonacoEditor = () => {
    monacoEditor = monaco.editor.create(monacoEditorRef.value, {
      theme: 'vs-dark', // 主题 vs vs-dark hc-black
      value: '', // 默认显示的值
      language: 'csharp',
      formatOnPaste: true,
      wordWrap: 'on', //自动换行，注意大小写
      wrappingIndent: 'indent',
      folding: true, // 是否折叠
      foldingHighlight: true, // 折叠等高线
      foldingStrategy: 'indentation', // 折叠方式  auto | indentation
      showFoldingControls: 'always', // 是否一直显示折叠 always | mouSEOver
      disableLayerHinting: true, // 等宽优化
      emptySelectionClipboard: false, // 空选择剪切板
      selectionClipboard: false, // 选择剪切板
      automaticLayout: true, // 自动布局
      codeLens: false, // 代码镜头
      scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
      colorDecorators: true, // 颜色装饰器
      accessibilitySupport: 'auto', // 辅助功能支持  "auto" | "off" | "on"
      lineNumbers: 'on', // 行号 取值： "on" | "off" | "relative" | "interval" | function
      lineNumbersMinChars: 5, // 行号最小字符   number
      //enableSplitViewResizing: false,
      readOnly: true //是否只读  取值 true | false
    });
  };
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields(props.data);
          isUpdate.value = true;
          // Http请求
          if (props.data.id && form.createType === JobCreateTypeEnum.NUMBER_2) {
            state.httpJobMessage = getHttpJobMessage(form.properties);
          }
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }

      setTimeout(() => {
        if (monacoEditor == null) initMonacoEditor();
        monacoEditor.setValue(
          form.scriptCode ? form.scriptCode : JobScriptCode
        );
      }, 500);
    }
  );

  // 根据任务属性获取 HttpJobMessage
  const getHttpJobMessage = (
    properties: string | undefined | null
  ): HttpJobMessage => {
    if (properties === undefined || properties === null || properties === '')
      return {};

    const propData = JSON.parse(properties);
    const httpJobMessageNet = JSON.parse(propData['HttpJob']); // 后端大写开头的 HttpJobMessage

    return {
      requestUri: httpJobMessageNet.RequestUri,
      httpMethod: JSON.stringify(httpJobMessageNet.HttpMethod),
      body: httpJobMessageNet.Body
    };
  };

  // HTTP 作业消息（字段定义来源 Furion 的 HttpJobMessage）
  interface HttpJobMessage {
    requestUri?: string;
    httpMethod?: string;
    body?: string;
  }
</script>
